import { getShopCategory, getShopGoods } from "../../../api/shop"

Page({
  data: {
    member_id: '',
    cateList: [],
    activeCateId: 0,
    sortData: [
      { id: 1, name: '综合排序' },
      { id: 2, name: '价格升序' },
      { id: 3, name: '价格降序' },
      { id: 4, name: '最新上架' }
    ],
    currentSort: { id: 1, name: '综合排序' },
    showFilter: false,
    page: 1,
    pageSize: 10,
    last_page: 1,
    goodsList: [],
    goods_name: '',
    shopname: ''
  },
  itemClick(e) {
    this.setData({
      currentSort: e.currentTarget.dataset.item,
      showFilter: false
    });
    this.getGoods();
  },
  showSort() {
    this.setData({
      showFilter: !this.data.showFilter
    })
  },
  cateClick(e) {
    const id = e.currentTarget.dataset.id;
    if (id != this.data.activeCateId) {
      this.setData({
        activeCateId: id,
        currentSort: { id: 1, name: '综合排序' }
      })
      this.getGoods();
    }
  },
  onLoad(options) {
    this.setData({
      shopname: options.shopname,
      member_id: options.member_id
    })
    this.getData();
  },
  getGoods(flag) {
    // flag为true时加载更多 
    const { activeCateId: cate_id, member_id, currentSort, page, pageSize } = this.data;
    getShopGoods({
      member_id,
      cate_id,
      goods_name: '',
      sort_data: currentSort.id,
      page: flag ? page + 1 : 1,
      pageSize
    }).then(res => {
      let list = [...this.data.goodsList];
      if (flag) {
        list = [...list, ...res.data];
      } else {
        list = res.data;
      }
      this.setData({
        goodsList: list,
        page: res.current_page,
        last_page: res.last_page
      })
    });
  },
  getData() {
    getShopCategory(this.data.member_id).then(res => {
      if (res && res.length > 0) {
        this.setData({
          cateList: res,
          activeCateId: res[0].id
        });
        this.getGoods();
      }
    });
  },
  reachListBottom(e) {
    const { page, last_page } = this.data;
    if (page < last_page) {
      this.getGoods(true);
    }
  },
  handleSubmit(value) {
    if (!value) {
      return;
    }
    this.setData({
      goods_name: ''
    });
    my.navigateTo({
      url: '../search/search?goods_name=' + value + '&member_id=' + this.data.member_id
    })
  },
  handleInput(value) {
    this.setData({ goods_name: value });
  },
  handleClear(value) {
    this.setData({ goods_name: '' });
  }
});
